package com.njrsrc.android.tasks;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.Company;
import com.njrsrc.android.bean.HrLetterInfo;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class HrLetterDetailTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler mHandler;
	private UserInfo userInfo;
	private HrLetterInfo hrLetterInfo;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		mHandler = (Handler) params[0];
		url = (String) params[1];
		userInfo = (UserInfo) params[2];
		hrLetterInfo = (HrLetterInfo) params[3];
		JSONObject jsonObject = Helpers.getJSONArrayByGet(url);
		Message msg = mHandler.obtainMessage();
		try {
			if(jsonObject == null)
			{
				msg.what = MsgID.HR_LETTER_DETAIL_QUERY_ERROR;
			}
			else if (jsonObject.toString().contains("error_code")) {
				// 返回错误
				userInfo.setError_code(jsonObject.getString("error_code"));
				userInfo.setError_message(jsonObject.getString("error_message"));
				msg.what = MsgID.HR_LETTER_DETAIL_QUERY_FAIL;
			} else {
				msg.what = MsgID.HR_LETTER_DETAIL_QUERY_SUCCESS;
				hrLetterInfo.setHr_letter_id(jsonObject.getString("hr_letter_id"));
				hrLetterInfo.setTitle(jsonObject.getString("title"));
				hrLetterInfo.setSent_at(jsonObject.getString("sent_at"));
				hrLetterInfo.setType(jsonObject.getString("type"));
				hrLetterInfo.setStatus(jsonObject.getString("status"));
				hrLetterInfo.setRead_at(jsonObject.getString("read_at"));
				hrLetterInfo.setBody(jsonObject.getString("body"));
				if(!"null".equals(jsonObject.getString("company")) 
						&& jsonObject.getString("company") != null)
				{
					JSONObject companyJsonObject = jsonObject.getJSONObject("company");
					Company company = new Company();
					company.setCompany_id(companyJsonObject.getString("company_id"));
					company.setName(companyJsonObject.getString("name"));
					company.setLogo_url(companyJsonObject.getString("logo_url"));
					company.setAddress(companyJsonObject.getString("address"));
					hrLetterInfo.setCompany(company);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHandler.sendMessage(msg);
		return null;
	}
}